package com.itheima.tlias.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias.common.result.Result;
import com.itheima.tlias.mapper.EmpMapper;
import com.itheima.tlias.pojo.entity.Emp;
import com.itheima.tlias.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 登录拦截器 由 Spring容器提供
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private EmpMapper empMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("开始执行http请求过滤");
        //参数向下转型成HttpServletRequest 以及HttpServletResponse


//        //放行登录接口
//        String requestURI = request.getRequestURI();
//        if (requestURI.contains("login")) {
//            return true;
//        }

        //获取请求头中的token
        String token = request.getHeader("token");
        //判断是否有token——是否绕过登录
        if (Objects.isNull(token)) {

            writeErrorResponse(response,"请先登录");
            return false;
        }
        //使用jwt验证 token
        //验证token合法性
        try{
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
            if (Objects.isNull(emp)|| !emp.getPassword().equals(jsonObject.getString("password"))){
                writeErrorResponse(response,"token不合法或者已过期");
                return false;
            }
        }catch (Exception e){
            writeErrorResponse(response,"token不合法或者已过期");
            return false;
        }


        //过滤链对象执行完成过滤逻辑之后放行http请求，把request和response重新交给controller(servlet)
        log.info("过滤完成");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
    private static void writeErrorResponse(HttpServletResponse servletResponse,String msg) throws IOException {
        servletResponse.setContentType("application/json; charset=UTF-8");
        //设置UTF-8编码
        servletResponse.setCharacterEncoding("UTF-8");
        servletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
        Result error = Result.error(msg);
        PrintWriter writer = servletResponse.getWriter();
        //使用fastjson 把对象转成json字符串
        writer.write(JSONObject.toJSONString(error));
    }
}
